package starkuz.lg.tools;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.util.List;


public class StyleCleanerJSOUP {
    public static String cleanTags(String html) {
        if (html.isEmpty()) {
            return "";
        }
        Document doc = Jsoup.parse(html);
        Element formElement = doc.getElementsByTag("form").get(0);
        List<Element> inputs = doc.getElementsByTag("input");
        List<Element> tables = doc.getElementsByTag("table");
        if (formElement == null) {
            return "";
        }
        if (tables == null || tables.isEmpty()) {
            return "";
        }
        if (!tables.isEmpty()) {
            tables.get(0).remove();
            for (Element ch : inputs) {
                formElement.appendChild(ch);
            }
        }
        List<Element> elementsStyle = doc.getAllElements();
        for (Element element : elementsStyle) {
            if (element.attr("type").equals("text")) {
                element.attr("class", "field");
            }
            element.removeAttr("style");
            if (element.tagName().equals("table")) {
            }
        }
        List<Element> elementsSubmit = doc.getElementsByAttributeValue("type", "submit");
        for (Element element : elementsSubmit) {
            element.removeAttr("class");
            element.addClass("submit");
        }
        return formElement.toString();
    }

    public static String getInputs(String html) {
        if (html.isEmpty()) {
            return "";
        }
        Document doc = Jsoup.parse(html);
        List<Element> elementsStyle = doc.getAllElements();
        for (Element element : elementsStyle) {
            if (element.attr("type").equals("text")) {
                element.attr("class", "field");
            }
            element.removeAttr("style");
            if (element.tagName().equals("table")) {
            }
        }
        List<Element> elementsSubmit = doc.getElementsByAttributeValue("type", "submit");
        for (Element element : elementsSubmit) {
            element.removeAttr("class");
            element.addClass("submit");
        }
        List<Element> inputs = doc.getElementsByTag("input");
        if (inputs != null && !inputs.isEmpty()) {
            return inputs.toString();
        }
        return "";
    }

    public static String getAction(String html) {
        if (html.isEmpty()) {
            return "";
        }
        Document doc = Jsoup.parse(html);
        List<Element> forms = doc.getElementsByTag("form");
        if (forms == null || forms.isEmpty()) {
            return "";
        }
        Element formElement = forms.get(0);
        if (formElement == null) {
            return "";
        }
        return formElement.attr("action");
    }


}
